<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jsonp 实现跨域</title>
</head>
<body>
    <h3>jsonp 实现跨域</h3>

    <script>
        function Jsonp(url, cb) {
            this.callbackName = 'jsonp_' + Date.now()
            this.cb = cb
            this.url = url
            this.init()
        }

        Jsonp.prototype.init = function() {
            if(~this.url.indexOf('?')) {
                this.url = this.url + '&callback=' + this.callbackName
            } else {
                this.url = this.url + '?callback=' + this.callbackName
            }
            this.createCallback()
            this.createScript()
        }

        Jsonp.prototype.createScript = function() {
            var script = document.createElement('script')
            script.src = this.url
            script.onload = function() {
                this.remove()
                // 删除 window 下定义的无用方法
                delete window[this.callbackName]
            }
            document.body.appendChild(script)
        }

        Jsonp.prototype.createCallback = function() {
            window[this.callbackName] = this.cb
        }
        new Jsonp('http://localhost:8888/', function(data) {
            console.log(data)
        })
    </script>
</body>
</html>